package app.server.project.main.service.service.task;

import app.server.project.core.constants.Def;
import app.server.project.core.http.CMSLstResp;
import app.server.project.main.service.db.dao.cfg.LangCfgDao;
import app.server.project.main.service.db.dao.cfg.TaskCfgDao;
import app.server.project.main.service.db.entity.cfg.LangCfgEntity;
import app.server.project.main.service.db.entity.cfg.TaskCfgEntity;
import app.server.project.main.service.service.cms.GMService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Comparator;
import java.util.Objects;

@RequiredArgsConstructor
@Service
public class TaskCfgService {

    private final LangCfgDao langCfgDao;
    private final TaskCfgDao taskCfgDao;
    private final GMService gmService;


    /**
     * @param typeId
     * @return
     */
    public CMSLstResp<LangCfgEntity> getLang(long lid) {
        var lst = this.langCfgDao.getTypeMap().get(lid);
        return CMSLstResp.of(lst, lst == null ? 0 : lst.size());
    }


    public void addLang(LangCfgEntity langCfgEntity) {
        langCfgEntity.setId(String.format("%s_%s", langCfgEntity.getLid(), langCfgEntity.getType()));
        this.langCfgDao.del(langCfgEntity.getId());
        this.langCfgDao.save(langCfgEntity);
        this.langCfgDao.init();
    }


    public void delLang(LangCfgEntity langCfgEntity) {
        this.langCfgDao.del(langCfgEntity.getId());
        this.langCfgDao.init();
    }

    public CMSLstResp<TaskCfgEntity> getTaskCfg() {
        var lst = this.taskCfgDao.getAllLst();
        lst.stream().sorted(Comparator.comparingInt(TaskCfgEntity::getOrderIndex));
        return CMSLstResp.of(lst, Objects.isNull(lst) ? Def.Zero : lst.size());
    }

    public void addTaskCfg(TaskCfgEntity taskCfgEntity) {
        taskCfgEntity.setId(this.taskCfgDao.getMaxId() + 1);
        this.taskCfgDao.save(taskCfgEntity);
        this.taskCfgDao.init();
    }

    public void editTaskCfg(TaskCfgEntity taskCfgEntity) {
        this.taskCfgDao.saveOrUpdate(taskCfgEntity);
        this.taskCfgDao.init();
    }

    public void delTaskCfg(TaskCfgEntity taskCfgEntity) {
        this.taskCfgDao.del(taskCfgEntity);
        this.taskCfgDao.init();
    }

    public void uploadSingleImg(MultipartFile files, int taskId) {
        var imgUrl = this.gmService.uploadSingleImg(files);
        var taskCfgEntity = this.taskCfgDao.getOneByTaskId(taskId);
        taskCfgEntity.setImg(imgUrl);
        this.taskCfgDao.saveOrUpdate(taskCfgEntity);
        this.taskCfgDao.init();

    }
}
